package org.jsola.hr.web;

import com.alipay.api.domain.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.CertificateSendCodeDTO;
import org.jsola.hr.dto.EmpModifyPhoneAddDTO;
import org.jsola.hr.dto.SendCodeDTO;
import org.jsola.hr.provider.IPermissionProviderService;
import org.jsola.hr.service.IChannelService;
import org.jsola.hr.service.IEmpInfoService;
import org.jsola.hr.service.IEmpModifyPhoneService;
import org.jsola.hr.service.ISaleUserService;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.jsola.user.entity.UserDO;
import org.jsola.user.service.ICertificationService;
import org.jsola.user.service.IUserPermissionService;
import org.jsola.user.service.IUserService;
import org.jsola.user.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

import static org.jsola.user.constant.ExceptionConstant.VERIFICATION_NOT_RIGHT;

@RestController
@RequestMapping(HrConstants.API_PATH + "/v1/certifications")
@Slf4j
public class HrCertificationController {

    /**
     * 通用场景验证码场景
     */
    public static final String COMMON_SCENE = "common";

    /**
     * 管理员更新手机号场景
     */
    public static final String ADMIN_UPDATE_PHONE_SCENE = "admin_update_phone";

    @Autowired
    private ICertificationService certificationService;

    @Autowired
    private IPermissionProviderService permissionProviderService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IChannelService channelService;

    @Autowired
    private ISaleUserService saleUserService;

    @Autowired
    private IEmpModifyPhoneService empModifyPhoneService;

    @Autowired
    private IEmpInfoService empInfoService;

    /**
     * 发送短信
     * @param sendCodeDTO
     * @return
     */
    @PostMapping( value = "/sendCodeByScene")
    public Result<Boolean> sendCodeByScene(@RequestBody @Valid SendCodeDTO sendCodeDTO) {
        TokenUser tokenUser = UserContext.getUser();

        //发送
        String scenc = sendCodeDTO.getScene();
        switch (scenc){
            case COMMON_SCENE:
                //通用场景不需要校验
                break;
            case ADMIN_UPDATE_PHONE_SCENE:
                //校验新手机号是否已存在，如果已存在抛出异常
                boolean flag = permissionProviderService.isHrAdmin(sendCodeDTO.getPhone(), tokenUser);
                if (flag) {
                    return Result.fail("该手机号已是管理员账号");
                }
                UserDO userDO = userService.selectByPhone(sendCodeDTO.getPhone());
                if (userDO != null) {
                    return Result.fail("该手机号已注册");
                }
                break;
            default:
        }
        return certificationService.sendCodeWithoutUser(sendCodeDTO.getPhone(), scenc, tokenUser);
    }

    /**
     * 验证短信
     * @param certificateSendCodeDTO
     * @return
     */
    @PostMapping("/certificateCodeByScene")
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public Result<Boolean> updatePhone(@Valid @RequestBody CertificateSendCodeDTO certificateSendCodeDTO) {
        TokenUser tokenUser = UserContext.getUser();

        log.info("更新手机号certificateSendCodeDTO:{}",certificateSendCodeDTO);

        String scene =  certificateSendCodeDTO.getScene();

        Boolean isSuccess = certificationService.checkCodeWithUser(certificateSendCodeDTO.getCode(),
                certificateSendCodeDTO.getPhone(),
                scene,
                tokenUser);

        if (!isSuccess) {
            throw new ParamException(VERIFICATION_NOT_RIGHT);
        }

        //特殊场景验证码
        switch (scene){
            case COMMON_SCENE:
                //通用场景不需要后续逻辑处理
                break;
            case ADMIN_UPDATE_PHONE_SCENE:
                //验证码正确，修改user表手机号
                UserVO userVO = userService.selectById(tokenUser.getUserId());
                userService.updateUserPhone(tokenUser.getUserId(), certificateSendCodeDTO.getPhone(), tokenUser);

                //判断是不是销售、渠道，花名册员工、同步更新
                saleUserService.updatePhone(tokenUser.getUserId(), certificateSendCodeDTO.getPhone());

                channelService.updatePhone(tokenUser.getUserId(), certificateSendCodeDTO.getPhone());

                empInfoService.updatePhoneById(tokenUser.getUserId(), certificateSendCodeDTO.getPhone());

                //记录更新日志
                EmpModifyPhoneAddDTO empModifyPhoneAddDTO = new EmpModifyPhoneAddDTO();
                empModifyPhoneAddDTO.setOldPhone(userVO.getPhone());
                empModifyPhoneAddDTO.setNewPhone(certificateSendCodeDTO.getPhone());
                empModifyPhoneAddDTO.setOldUserId(tokenUser.getUserId());
                empModifyPhoneAddDTO.setNewUserId(tokenUser.getUserId());
                empModifyPhoneAddDTO.setRemark("管理员更换手机号");
                empModifyPhoneService.save(empModifyPhoneAddDTO, tokenUser);

                break;
            default:
        }

        return Result.success(isSuccess);
    }

}
